﻿/**************************************************************
 *
 * 唯一标识：6efab944-b48c-4979-b670-6494f42d3c14
 * 命名空间：Sgr.UPMS.Application.Commands.Users
 * 创建时间：2023/8/27 12:47:15
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：修改用户命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.Application.Queries;
using Sgr.UPMS.Domain.Users;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.UserProfile
{
    /// <summary>
    /// 修改用户命令处理器
    /// </summary>
    public class ModifyUserCommandHandle : IRequestHandler<ModifyUserCommand, CommandResult<bool>>
    {
        private readonly IUserRepository _userRepository;
        private readonly ICurrentUser _currentUser;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="currentUser">当前用户信息</param>
        public ModifyUserCommandHandle(IUserRepository userRepository, ICurrentUser currentUser)
        {
            _userRepository = userRepository;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 处理修改用户命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(ModifyUserCommand request, CancellationToken cancellationToken)
        {
            long userId = QueryHelper.GetUserId(_currentUser);

            // 查找用户实体
            var user = await _userRepository.GetAsync(userId, cancellationToken);

            // 如果找不到用户，返回NotFound结果
            if (user == null)
                return CommandResult.NotFound<bool>("未找到指定的用户");

            user.SetUserInfo(request.UserName, request.Gender, request.QQ, request.BirthDay);

            // 更新到仓储
            await _userRepository.UpdateAsync(user, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "用户信息修改成功");
        }
    }
}